<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改用户信息"
    width="30%"
    center
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form label-width="80px" :model="formData">
      <el-form-item label="密码" style="width: 85%" prop="password">
        <el-input type="password" show-password v-model="formData.password" />
      </el-form-item>
      <el-form-item label="年龄" style="width: 85%" prop="age">
        <el-select-v2
          v-model="formData.age"
          style="width: 100%"
          placeholder="请输入年龄"
          :options="options"
        />
      </el-form-item>
      <el-form-item label="性别" style="width: 85%" prop="gender">
        <el-select style="width: 100%" v-model="formData.gender">
          <el-option label="男" :value="0" />
          <el-option label="女" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="头像" style="width: 85%" prop="avatar">
        <el-upload
          v-model:file-list="fileList"
          list-type="picture-card"
          ref="uploadRef"
          class="avatar-uploader"
          action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
          :show-file-list="true"
          :auto-upload="false"
          :limit="1"
          :on-change="handleAvatarSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="imgDialogVisible">
          <img w-full :src="avatarUrl" alt="预览图片" />
        </el-dialog>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="warning" @click="changeVisible">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect, computed } from 'vue'
import { uploadUserAvatarAPI } from '@/http/user'
import { createBufferHashName } from '@/utils/utils'
import { useUserStore } from '@/store/userStore'
import { Md5 } from 'ts-md5'
import { deleteAvatarFileAPI } from '@/http/user'
import type { AvatarFileResType } from '@/interface/user/userType'

const userStore = useUserStore()
const dialogVisible = ref(false)
const imgDialogVisible = ref(false)
const uploadRef = ref()
// 年龄下拉框
const options = new Array(100).fill(0).map((_, index) => {
  return {
    value: `${index + 1}`,
    label: `${index + 1}`
  }
})

let avatarUrl = ref<string>('') //服务器返回的图像地址

const formData: any = reactive({
  password: '',
  age: '',
  gender: 0,
  avatar: '' //处理后的文件名，访问的时候拼接服务器地址接口
})
// 如果用户已经有图片了需要放在这里展示
const fileList: any = reactive([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])

// // 回显默认数据
watchEffect(() => {
  formData.password = userStore.userInfoDetail?.password || ''
  formData.age = userStore.userInfoDetail?.age || 1
  formData.gender = userStore.userInfoDetail?.gender || 0
  // @ts-ignore
  formData.avatar = userStore.userInfoDetail?.avatar || ''
  // @ts-ignore
  if (userStore.userInfoDetail.avatar && fileList.length === 0) {
    console.log('执行', fileList.length)

    // 只有用户头像存在并且数组中没有插入头像回显的时候才会进行插入操作
    fileList.push({
      name: userStore.userInfoDetail?.avatar,
      // @ts-ignore
      url: `${import.meta.env.VITE_BASE_URL}upload/${userStore.userInfoDetail?.avatar}`
    })
  }
})

const changeVisible = () => {
  dialogVisible.value = !dialogVisible.value
}

// 上传图片前校验
const handleAvatarSuccess = async (file: any) => {
  if (!/(jpe?g|png|gif)/i.test(file.raw.name.split('.')[1])) {
    ElMessage({
      type: 'error',
      message: '图片格式不正确'
    })
    // 清空文件列表
    uploadRef.value.clearFiles()
    return
  }
  // 优先将文件提交给服务器处理，服务器返回文件名
  try {
    let { filename } = (await createBufferHashName(file.raw)) as any
    let res: AvatarFileResType = await uploadUserAvatarAPI(file.raw, filename)
    if (res.code === 200) {
      formData.avatar = filename
      ElMessage({
        type: 'success',
        message: '图片上传成功'
      })
    }
  } catch (error) {}
}

const handlePictureCardPreview = (uploadFile: any) => {
  //
  fileList.push({ url: uploadFile.url!, name: uploadFile.name })
  // 本地预览展示，自动转换为blob格式
  avatarUrl = uploadFile.url!
  imgDialogVisible.value = true
}

// 删除用户头像
const handleRemove = async () => {
  // 需要用到头像文件名和id
  try {
    let res: any = await deleteAvatarFileAPI({
      _id: userStore.userInfoDetail?._id,
      avatar: userStore.userInfoDetail?.avatar
    })
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除头像成功'
      })
      fileList.pop()
      await userStore.getUserInfoDetailAction()
    } else {
      ElMessage({
        type: 'error',
        message: '删除头像失败'
      })
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '删除头像失败'
    })
  }
}

// 处理数据修改
const handleSubmit = async () => {
  try {
    // 密码加密走加密流程
    const md5 = new Md5()
    let md5pasw = md5.appendAsciiStr(formData.password).end()
    let config = { ...formData, md5pasw }

    // @ts-ignore
    await userStore.updateUserInfo(userStore.userInfoDetail?._id, config)
    await userStore.getUserInfoDetailAction()
    // 关闭弹窗
    dialogVisible.value = false
  } catch (error) {}
}

defineExpose({
  changeVisible
})
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
